﻿using GameControl;
using GameMap;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using UnityEngine;
using QxFramework.Core;
public class PosFixedItem : Item
{
    public PosFixedItemField Setting;
    public override ItemField ItemFieldSetting { get => Setting; set => Setting = (PosFixedItemField)value; }

    public override Sprite Sprite => this.GetComponent<SpriteRenderer>().sprite;

    public override ItemField UploadInstanceField()
    {
        ItemFieldSetting = base.UploadInstanceField();
   //     Setting.Rotation = transform.eulerAngles.z;
        float siz = MapManager. meshSize;
        (ItemFieldSetting as PosFixedItemField).MeshPosition = new Vector3Int(Mathf.RoundToInt((transform.position.x-GetField<PosFixedItemField>().MeshSize.x/2f*siz+siz/2f)/siz), Mathf.RoundToInt((transform.position.y - GetField<PosFixedItemField>().MeshSize.y/ 2f * siz + siz / 2f)/siz),
            GetField<PosFixedItemField>().MeshPosition.z);
        return ItemFieldSetting;
    }

    public override void DownloadInstanceField(object args)
    {
        base.DownloadInstanceField(args);
        ItemFieldSetting = args as PosFixedItemField;
   //     Debug.Assert(Setting != null);
        float siz = MapManager.meshSize;
        var tp = (Vector3)GetField<PosFixedItemField>().MeshSize / 2f*siz - Vector3.one * siz / 2f;
        tp = tp + (Vector3)GetField<PosFixedItemField>().MeshPosition * siz;
        tp.z = GetField<PosFixedItemField>().MeshPosition.z;
        transform.position =tp;
     //   transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, Setting.Rotation);
    }

    public override void OnStart()
    {
    //    throw new NotImplementedException();
    }
    public static float ForceToMakeSmokeThreshold = 100;
    public override void OnCollisionEnter2D(Collision2D collision)
    {
        base.OnCollisionEnter2D(collision);
        if (collision.GetImpactForce() > ForceToMakeSmokeThreshold)
        {
            var vtr =collision.transform.TransformVector(collision.GetNormal());
     //      Debug.Log("Vtr:"+vtr+"Pos:"+ collision.GetCotactPos());
            EffectsManager.Instance.Open("Smoke", collision.GetCotactPos(),"Smoke_"+UnityEngine.Random.value,
                new Tuple<float, Vector2>(collision.GetImpactForce(),vtr));
      //      this.transform.position - vtr.normalized * MapManager.meshSize / 2f
        }
    }
}
[Serializable]
public class PosFixedItemField : ItemField
{
    /// <summary>
    /// 网格z轴和世界z轴数值相同
    /// </summary>
    public Vector3Int MeshPosition;
    public Vector3Int MeshSize;
    //public float Rotation;
}